package com.tl.commonlibrary.network;

import android.text.TextUtils;

import com.tl.commonlibrary.AppConfig;
import com.tl.commonlibrary.BuildConfig;
import com.tl.commonlibrary.R;
import com.tl.commonlibrary.network.bean.base.BaseBean;
import com.tl.commonlibrary.tool.Logger;
import com.tl.commonlibrary.tool.UIUtils;
import com.tl.libmanager.MainAppInterface;
import com.tl.libmanager.PluginManager;

import java.io.IOException;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 2017/6/9 0009.
 */

public class RequestCallBack<T> implements Callback<T> {
    public static final String TAG = "OkHttp";
    public static final String FAILED_WRONG_FORMAT = "100";//格式错误
    public static final String FAILED_BUSINESS = "200";//业务处理异常
    public static final String FAILED_DATA = "300";//数据处理异常
    public static final String NETWORK_ERROR = "-1000";
    private RequestListener<T> listener;
    private boolean foreground = true;//是否是前台请求，如果不是，toast会被禁止

    public RequestCallBack foreground(boolean foreground) {
        this.foreground = foreground;
        return this;
    }

    public RequestCallBack(RequestListener<T> listener) {
        this.listener = listener;
    }

    @Override
    public void onResponse(Call<T> call, Response<T> response) {
        if (response.isSuccessful()) {
            //请求返回了实体数据
            onSuccess(call, response);
        } else {
            //跟网络设备相关的失败情况
            onNetError(call, response);
        }
    }

    @Override
    public void onFailure(Call<T> call, Throwable t) {
        if (foreground) {
            UIUtils.showToast(R.string.net_error);
        }
        Logger.e(TAG, t.getLocalizedMessage());
        if (listener != null) {
            ErrorResponse errorResponse = new ErrorResponse();
            errorResponse.msg = t.getMessage();
            errorResponse.code = NETWORK_ERROR;
            listener.onFailed(call, errorResponse);
        }
    }

    private void onSuccess(Call<T> call, Response<T> response) {
        if (response.body() instanceof BaseBean) {
            BaseBean bean = (BaseBean) response.body();
            if (bean.isSuccessful()) {//请求成功
                if (listener != null) {
                    listener.onSuccess(call, response.body());
                }
            } else if (bean.isTokenInvalid()) {//重新登录
                MainAppInterface mainAppInterface = PluginManager.get().getMainAppEntrance();
                if (mainAppInterface != null) {
                    mainAppInterface.tokenInvalid();
                }
                dataError(call, bean, false);
            } else {//数据方面请求失败
                dataError(call, bean, true);
            }
        } else {
            //返回数据结构没有继承BaseBean类的情况，自己去处理
            if (listener != null) {
                listener.onSuccess(call, response.body());
            }
        }
    }

    private void dataError(Call<T> call, BaseBean bean, boolean hint) {
        ErrorResponse errorResponse = new ErrorResponse();
        errorResponse.code = bean.code;
        errorResponse.msg = bean.msg;
        if (bean.code == FAILED_BUSINESS || bean.code == FAILED_WRONG_FORMAT || bean.code == FAILED_DATA) {
            Logger.e("OkHttp:", "code = " + bean.code + "---msg = " + bean.msg);
        } else if (foreground && hint && AppConfig.appContext != null && !TextUtils.isEmpty(errorResponse.msg)) {
            UIUtils.showToast(errorResponse.msg);
        }
        if (listener != null) {
            listener.onFailed(call, errorResponse);
        }
    }

    private void onNetError(Call<T> call, Response<T> response) {
        int code = response.code();
        ErrorResponse errorResponse = new ErrorResponse();
        if (code >= 400 && code < 500) {
            errorResponse.msg = response.message();
            errorResponse.code = "" + code;
            if (BuildConfig.DEBUG) {
                Logger.e(TAG, "onNetError: code=" + code);
                Logger.e(TAG, "onNetError: message=" + response.message());
            }
        } else {
            if (foreground && code >= 500 && AppConfig.appContext != null) {
                UIUtils.showToast(R.string.net_server_error);
            }
            String error = null;
            try {
                error = response.errorBody() != null ? response.errorBody().string() : "";
            } catch (IOException e) {
                e.printStackTrace();
            }
            errorResponse.msg = error;
            errorResponse.code = NETWORK_ERROR;
        }
        if (listener != null) {
            listener.onFailed(call, errorResponse);
        }
    }
}
